package com.bw.controller.aliPay;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.Invoice.PiPayLog;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.order.PiOrder;
import com.bw.entity.order.PiOrderItem;
import com.bw.entity.order.PiOrderLog;
import com.bw.resp.ResponseResult;
import com.bw.service.Invoice.IPiPayLogService;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.order.IPiOrderLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.service.user.ITbUserService;
import com.bw.utils.aliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/aliPay")
public class AliPayController {
    public final Logger logger = LoggerFactory.getLogger(AliPayController.class);
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private IPiPayLogService iPiPayLogService;
    @Autowired
    private ITbUserService iTbUserService;
    @Autowired
    private IPiOrderLogService iPiOrderLogService;
    @Autowired
    private IPiCustomerService iPiCustomerService;

    @GetMapping("/pay/{code}/{id}")
    public ResponseResult pay(@PathVariable String code, @PathVariable long id) {
        logger.info("调用支付开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("code", code);
            PiOrder piOrder = iPiOrderService.getOne(wrapper);
            result = iPiOrderService.payAgin(piOrder, id);

            //添加订单记录
            PiOrderLog orderLog=new PiOrderLog();
            orderLog.setOrderId(piOrder.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(id);
            orderLog.setRemarks("发起支付");
            orderLog.setUserName(iPiCustomerService.getById(id).getName());
            iPiOrderLogService.saveOrUpdate(orderLog);

        } catch (Exception e) {
            logger.error("调用支付失败" + e.toString());
            result.setSuccess(false);
            result.setMessage("调用支付失败" + e.toString());
        }
        logger.info("调用支付结束");
        return result;
    }

    @PostMapping("/checkSign")//支付宝同步通知接口，验证签名
    public ResponseResult checkSign(HttpServletRequest request, @RequestBody PiCustomer piCustomer) {
        logger.info("验证签名开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String code = request.getParameter("out_trade_no");//获取订单编号
            String trade_no = new String(request.getParameter("WIDTQtrade_no").getBytes("ISO-8859-1"),"UTF-8");

            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            /*
             * 添加支付记录
             * */
            logger.info("添加支付记录");
            String trade_amount = request.getParameter("total_amount");
            PiPayLog piPayLog = new PiPayLog();
            piPayLog.setCreateTime(new Date());//支付日期
            piPayLog.setOutTradeNo(code);//支付订单号



           // piPayLog.setUserId(id);//操作人id

            piPayLog.setTradeNo(trade_no);//交易号码
            piPayLog.setTradeNo(request.getParameter("trade_no"));//交易号
            piPayLog.setUserId(piCustomer.getId());//操作人id
            piPayLog.setTotalAmount(new BigDecimal(trade_amount));//付款金额
            piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信

            //添加订单记录
            PiOrderLog orderLog=new PiOrderLog();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",code);
            PiOrder piOrder1 = iPiOrderService.getOne(queryWrapper);
            orderLog.setOrderId(piOrder1.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(piOrder1.getTbId());
            orderLog.setUserName(piCustomer.getName());


            //验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if (signVerified) {
                piPayLog.setTradeState(1);//支付状态 0：支付中  1：支付成功  2：支付失败
                orderLog.setRemarks("支付成功");
                //验证签名成功,支付成功
                result.setMessage("恭喜您，支付成功！！！！！");
                //修改订单的状态为已支付
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("code", code);
                PiOrder piOrder = iPiOrderService.getOne(wrapper);
                piOrder.setState(4);
                iPiOrderService.saveOrUpdate(piOrder);
                //记录日志

            } else {
                piPayLog.setTradeState(2);//支付状态 0：支付中  1：支付成功  2：支付失败
                result.setSuccess(false);
                result.setMessage("支付失败");
            }
            iPiPayLogService.save(piPayLog);//添加支付记录表
            iPiOrderLogService.saveOrUpdate(orderLog);//添加订单记录表
            //返回结果

        } catch (Exception e) {
            logger.error("验证签名失败" + e.toString());
            result.setSuccess(false);
            result.setMessage("验证签名失败" + e.toString());
            /*
             * 添加支付记录
             * */
            logger.info("添加支付记录");
            PiPayLog piPayLog = new PiPayLog();
            piPayLog.setCreateTime(new Date());//支付日期
            piPayLog.setOutTradeNo(request.getParameter("out_trade_no"));//支付订单号



            //piPayLog.setUserId(id);//操作人id
            piPayLog.setTradeNo(request.getParameter("trade_no"));//交易号
            piPayLog.setUserId(piCustomer.getId());//操作人id
            piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
            piPayLog.setTradeState(2);//支付状态 0：支付中  1：支付成功  2：支付失败
            iPiPayLogService.save(piPayLog);

            //添加订单记录
            PiOrderLog orderLog=new PiOrderLog();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",request.getParameter("out_trade_no"));
            PiOrder piOrder1 = iPiOrderService.getOne(queryWrapper);
            orderLog.setOrderId(piOrder1.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(piOrder1.getTbId());
            orderLog.setRemarks("支付失败");
            orderLog.setUserName(piCustomer.getName());
            iPiOrderLogService.saveOrUpdate(orderLog);//添加订单记录表
        }
        logger.info("验证签名结束");
        return result;
    }

    /*
     *  根据订单编号查询当前订单的支付记录
     *  订单明细
     *  支付记录
     * */
    @PostMapping("/findpayLog")
    public ResponseResult findpayLog(@RequestBody PiOrder piOrder) {
        logger.info("查询订单的支付记录开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("out_trade_no", piOrder.getCode());
            List list = iPiPayLogService.list(wrapper);
            result.setResult(list);
        } catch (Exception e) {
            logger.error("查询订单的支付记录失败" + e.toString());
            result.setSuccess(false);
            result.setMessage("查询订单的支付记录失败" + e.toString());
        }
        logger.info("查询订单的支付记录结束");
        return result;
    }
}
